iT邦幫忙

2022 iThome 鐵人賽

DAY 20
0
自我挑戰組

30天 Neetcode解題之路系列 第 20

Day 20 - 20. Valid Parentheses

  • 分享至 

  • xImage
  •  

前言

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
那就開始今天的解題吧~


Question

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false

Constraints:

  • 1 <= s.length <= 10^4
  • s consists of parentheses only '()[]{}'.

Think

Code

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        pointer = -1
        
        for index in range(len(s)):
            print("Now s: ", s[index])
            ㄌ
            if s[index] == ')' or s[index] == ']' or s[index] == '}':]
                if index == 0:
                    return False
                else:
                    if len(stack) == 0:
                        return False
                    else:
                        bracket = stack.pop(-1)
                        if (bracket == '(' and s[index] == ')') or (bracket == '[' and s[index] == ']') or (bracket == '{' and s[index] == '}'):
                            pointer -= 1
                        else:
                            return False
            
            if s[index] == '(' or s[index] == '[' or s[index] == '{':
                stack.append(s[index])
                pointer += 1
        
        if len(stack) != 0:
            return False
        
        return True

Submission


今天就到這邊啦~
大家明天見/images/emoticon/emoticon29.gif


上一篇
Day 19 - 567. Permutation in String (By C++)
下一篇
Day 21 - 20. Valid Parentheses
系列文
30天 Neetcode解題之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言